package com.zoc.web.security;

import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zoc.service.prd.MemberService;
import com.zoc.service.security.UserService;
import com.zoc.common.SuperUtils;
import com.zoc.entity.prd.Member;
import com.zoc.entity.security.User;
import com.zoc.entity.security.UserRole;

/**
 * @author Super
 */
@Controller
@RequestMapping(value = "user")
public class UserController {

	private static final String MAIN_PAGE = "security/user";

	@Autowired
	private UserService userService;

	@Autowired
	private MemberService memberService;

	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	@RequestMapping(method = RequestMethod.GET)
	public String main() {
		return MAIN_PAGE;
	}

	@RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	List<User> list() {
		return userService.list(null);
	}

	@RequestMapping(value = "/userRoleList", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	List<UserRole> userRoleList(@RequestParam("key") String username) {
		return userService.selectUserRole(username);
	}

	@RequestMapping(value = "/updatePassword", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	String updatePassword(@RequestParam("data") String data) {
		try {
			logger.debug(data);
			User user = SuperUtils.parseObject(data, User.class);
			userService.updatePassword(user);
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "修改失败";
		}
	}

	@RequestMapping(value = "/save", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	String save(@RequestParam("data") String data, @RequestParam(value = "type", required = false) String type) {
		try {
			logger.debug(data);
			List<User> users = SuperUtils.parseArray(data, User.class);
			userService.batchSave(users);
			if ("M".equals(type)) { // Paradise Member
				List<Member> members = SuperUtils.parseArray(data, Member.class);
				for (Member m : members) {
					m.setLevel("-1");
					m.setRegister_date(new Date());
				}
				memberService.batchSave(members);
			}

			return "注册成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "注册失败";
		}
	}

}
